package com.hzw.saas.web.app.ticket;

import com.hzw.saas.api.ticket.ITicketAccessService;
import com.hzw.saas.api.ticket.bo.TicketCreateUserBO;
import com.hzw.saas.api.user.ICustomerService;
import com.hzw.saas.api.user.IUserAccountService;
import com.hzw.saas.api.user.IUserProfileService;
import com.hzw.saas.api.user.bo.CustomerBO;
import com.hzw.saas.api.user.bo.UserAccountBO;
import com.hzw.saas.api.user.bo.UserProfileBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import com.hzw.saas.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@RestController
@Api(tags = "工单")
@RequestMapping("/ticket")
@RequiredArgsConstructor
public class TicketController {

    private final ITicketAccessService ticketAccessService;
    private final IUserProfileService userProfileService;
    private final ICustomerService customerService;
    private final IUserAccountService userAccountService;

    @ApiOperationSort(1)
    @PostMapping("/access")
    @SysLog(operation = "工单接入")
    @ApiOperation(value = "工单接入", notes = "获取工单token，以及工单用户ID")
    public ResponseEntity<TicketCreateUserBO> accessToWorkOrder() {
        SaasUser user = SecurityUtils.getUser();
        UserProfileBO userProfileBO = userProfileService.get(user.getUserId());
        UserAccountBO userAccountBO = userAccountService.getAccount(user.getUserId());

        return ResponseEntity.ok(ticketAccessService.access(user.getUserId(), userProfileBO.getRealName(), userAccountBO.getPhoneNo(), userAccountBO.getEmail()));
    }

    @ApiOperationSort(2)
    @GetMapping("/accessEnable")
    @SysLog(operation = "工单是否可用(当前用户)")
    @ApiOperation(value = "工单是否可用(当前用户)", notes = "系统根据用户信息判断用户是否可启用工单功能")
    public ResponseEntity<Boolean> accessEnabled() {
        SaasUser user = SecurityUtils.getUser();
        CustomerBO customerBO = customerService.getCustomerByUserId(user.getUserId());
        boolean enabled = false;
        if(Objects.nonNull(customerBO)) {
            // 会员用户可启用（customer level>4）
            enabled = Integer.parseInt(customerBO.getCustomerLevel()) > 4;
        }
        return ResponseEntity.ok(enabled);
    }

}
